package cn.itcast.itcaststore.web.servlet;

import cn.itcast.itcaststore.domain.PageBean;
import cn.itcast.itcaststore.service.Impl.IProductService;
import cn.itcast.itcaststore.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ListProductServlet")
public class ListProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currentPage = request.getParameter("currentPage");
        String category = request.getParameter("category");

        String orderByDate="3";
        if (currentPage==null){
            currentPage="1";
        }
        if (category==null){
            category="全部商品";
        }
        PageBean pageBean = new PageBean();

        pageBean.setCurrentPage(Integer.parseInt(currentPage));
        pageBean.setOrderByDate(Integer.parseInt(orderByDate));
        pageBean.setCurrentPage(Integer.parseInt(currentPage));
        pageBean.setCategory(category);

        ProductService productService=new IProductService();

        //创建PageBean对象

        //返回所有符合条件的书籍
        List productList=productService.getListProduct(pageBean.getCategory(),pageBean.getCurrentPage(),pageBean.getOrderByDate());
        //返回所有符合条件的数据总数
        int totalDate=productService.getTotalDate(pageBean.getCategory());
        pageBean.setTotalDate(totalDate);

        if (pageBean.getTotalDate()%pageBean.getOrderByDate()==0){
            pageBean.setTotalPage(pageBean.getTotalDate()/pageBean.getOrderByDate());
        }else {
            pageBean.setTotalPage(pageBean.getTotalDate()/pageBean.getOrderByDate()+1);
        }

        request.setAttribute("bean",pageBean );
        request.setAttribute("productList",productList);

        request.getRequestDispatcher("/client/product_list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
